package com.example.as_sum.application;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.widget.Toast;

import com.example.as_sum.util.Log;


public class NetWorkService extends Service {
	private FZEGJReceiver receiver;
	private ConnectivityManager manager;
	private IntentFilter filter;
	private Toast toast;
	class FZEGJReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
				Log.e("------>", "网络状态改变了");
				if(AppApplication.aContext.isFirstNetwork == true) {
					//第一次
					checkNetWorkState(context);
					Log.e("------>", "第一次网络状态");
					AppApplication.aContext.isFirstNetwork=false;
				}else{
					//app登出
					Log.e("------>", "app要登出了");
					if(checkNetWorkState(context)) {
						//AppApplication.aContext.safetyLogout(context, false, false);
					}
				}
			}
		}
	}
	
	protected boolean checkNetWorkState(Context context) {
		NetworkInfo info = manager.getActiveNetworkInfo();
		if (info != null && info.isAvailable()) {
			AppApplication.aContext.netWorkState = true;
			return true;
		} else {
			AppApplication.aContext.netWorkState = false;
			toastShow(null);
			return false;
		}

	}
	private void toastShow(String s){
	  if(toast==null){
		 toast=Toast.makeText(this, "网络已切换，请重新登录", Toast.LENGTH_SHORT);
		}
		if(AppApplication.aContext.isRunningForeground(this)){
		       toast.show();
		}
	}
	@Override
	public void onCreate() {
		receiver = new FZEGJReceiver();
		filter = new IntentFilter();
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		this.registerReceiver(receiver, filter);
		manager = (ConnectivityManager) this
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		super.onCreate();
	}
	@Override
	public void onDestroy() {
		this.unregisterReceiver(receiver);
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		
		return null;
	}

}
